package com.lagou.edu.authority.controller;

import com.google.common.collect.Sets;
import com.lagou.edu.authority.dto.AllocateRoleMenuDTO;
import com.lagou.edu.authority.dto.MenuDTO;
import com.lagou.edu.authority.dto.MenuNodeDTO;
import com.lagou.edu.authority.entity.Menu;
import com.lagou.edu.authority.service.IMenuService;
import com.lagou.edu.common.util.ConverUtil;
import com.lagou.edu.common.util.ConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 菜单
 *
 * @author lm
 * @since 2021/11/4 15:42
 */
@Slf4j
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    IMenuService menuService;

    @PostMapping(value = "/saveOrUpdate")
    public Boolean saveOrUpdate(@RequestBody MenuDTO menuDTO) {
        Menu menu = ConvertUtils.convert(menuDTO, Menu.class);
        menu.setUpdatedTime(new Date());
        if (menu.getParentId() == -1) {
            menu.setLevel(0);
        } else {
            Menu parentMenu = menuService.getById(menu.getParentId());
            menu.setLevel(parentMenu.getLevel() + 1);
        }
        return menuService.saveOrUpdate(menu);
    }

    @GetMapping("/{id}")
    public Boolean deleteMenu(@PathVariable("id") Integer id) {
        return menuService.removeById(id);
    }

    /**
     * 获取所有菜单信息
     *
     * @return
     */
    @GetMapping("/getAll")
    public List<MenuDTO> getAllMenu() {
        return ConverUtil.convertList(menuService.list(), MenuDTO.class);
    }

    /**
     * 获取菜单树
     *
     * @return
     */
    @GetMapping("/getMenuNodeList")
    public List<MenuNodeDTO> getMenuNodeList() {
        return menuService.getMenuNodeList();
    }

    @GetMapping("/getMenuById")
    public MenuDTO getMenuById(@RequestParam("id") Integer id) {
        return ConverUtil.convert(menuService.getById(id), MenuDTO.class);
    }

    @GetMapping("/getMenuByRoleId")
    List<MenuDTO> getMenuByRoleId(@RequestParam("roleId") Integer roleId) {
        return ConverUtil.convertList(menuService.getMenuByRoleId(Sets.newHashSet(roleId)), MenuDTO.class);
    }

    /**
     * 给角色分配菜单
     *
     * @param allocateRoleMenuDTO
     * @return
     */
    @PostMapping("/allocateRoleMenus")
    Boolean allocateRoleMenus(@RequestBody AllocateRoleMenuDTO allocateRoleMenuDTO) {
        log.info("Allocate role menus with params:{}", allocateRoleMenuDTO);
        return menuService.allocateRoleMenus(allocateRoleMenuDTO);
    }
}
